package chapter12;

import chapter9.DynamicArray;

import java.util.*;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/20 13:33
 */
public class MyMap<K, V> extends AbstractMap<K, V> {
    private DynamicArray<Map.Entry<K, V>> dynamicArray;
    private Set<Map.Entry<K, V>> entrySet = null;

    public MyMap() {
        this.dynamicArray = new DynamicArray<>();
    }

    public MyMap(Map<? extends K, ? extends V> map) {
        this();
        putAll(map);
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Map.Entry<K, V>> set = entrySet;
        return set != null ? set : (entrySet = new EntrySet());
    }

    @Override
    public V put(K key, V value) {
        for (int i = 0; i < dynamicArray.size(); i++) {
            Map.Entry<K, V> entry = dynamicArray.get(i);
            if (key == null && key.equals(entry.getKey())
                    || (key != null && key.equals(entry.getKey()))) {
                V oldValue = entry.getValue();
                entry.setValue(value);
                return oldValue;
            }
        }
        Map.Entry<K, V> newEntry = new AbstractMap.SimpleEntry<>(key, value);
        dynamicArray.add(newEntry);
        return null;
    }

    class EntrySet extends AbstractSet<Map.Entry<K, V>> {

        @Override
        public Iterator<Entry<K, V>> iterator() {
            return dynamicArray.iterator();
        }

        @Override
        public int size() {
            return dynamicArray.size();
        }
    }
}
